package com.apkicon.processor;

import com.apkicon.model.IconInfo;
import com.apkicon.parser.ApkParserLibrary;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.InputStream;
import java.util.zip.ZipFile;

/**
 * PNG/WebP图标处理器
 * 参考Google bundletool的实现，提供高质量的PNG绘制
 */
public class PngIconProcessor implements IconProcessor {
    
    @Override
    public IconInfo processIcon(ApkParserLibrary.ApkInfo apkInfo, ApkParserLibrary.IconResource iconResource, int targetSize) throws Exception {
        try (ZipFile zipFile = new ZipFile(apkInfo.getApkFile())) {
            java.util.zip.ZipEntry entry = zipFile.getEntry(iconResource.getPath());
            if (entry == null) {
                throw new IllegalArgumentException("Icon resource not found: " + iconResource.getPath());
            }
            
            try (InputStream is = zipFile.getInputStream(entry)) {
                BufferedImage originalImage = ImageIO.read(is);
                if (originalImage == null) {
                    throw new IllegalArgumentException("Unable to read image from: " + iconResource.getPath());
                }
                
                // 调整尺寸
                BufferedImage resizedImage = resizeImage(originalImage, targetSize);
                
                IconInfo.IconType iconType = "webp".equals(iconResource.getType()) ? 
                    IconInfo.IconType.WEBP : IconInfo.IconType.PNG;
                
                return new IconInfo(resizedImage, iconType, iconResource.getPath());
            }
        }
    }
    
    /**
     * 调整图像尺寸 - 改进的高质量缩放实现
     */
    private BufferedImage resizeImage(BufferedImage originalImage, int targetSize) {
        int originalWidth = originalImage.getWidth();
        int originalHeight = originalImage.getHeight();
        
        // 如果尺寸已经符合要求，直接返回
        if (originalWidth == targetSize && originalHeight == targetSize) {
            return originalImage;
        }
        
        // 创建新的图像，使用ARGB格式确保透明度支持
        BufferedImage resizedImage = new BufferedImage(targetSize, targetSize, BufferedImage.TYPE_INT_ARGB);
        Graphics2D g2d = resizedImage.createGraphics();
        
        try {
            // 设置最高质量的渲染提示
            g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
            g2d.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
            g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
            g2d.setRenderingHint(RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY);
            g2d.setRenderingHint(RenderingHints.KEY_ALPHA_INTERPOLATION, RenderingHints.VALUE_ALPHA_INTERPOLATION_QUALITY);
            g2d.setRenderingHint(RenderingHints.KEY_DITHERING, RenderingHints.VALUE_DITHER_ENABLE);
            g2d.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_PURE);
            
            // 设置背景为透明
            g2d.setComposite(AlphaComposite.SrcOver);
            g2d.setBackground(new Color(0, 0, 0, 0));
            g2d.clearRect(0, 0, targetSize, targetSize);
            
            // 按照Android算法缩放
            drawAndroidScaledIcon(g2d, originalImage, targetSize);
            
        } finally {
            g2d.dispose();
        }
        
        return resizedImage;
    }
    
    /**
     * 按照Android算法绘制缩放后的图标
     */
    private void drawAndroidScaledIcon(Graphics2D g2d, BufferedImage originalImage, int targetSize) {
        int originalWidth = originalImage.getWidth();
        int originalHeight = originalImage.getHeight();
        
        // 计算缩放比例，保持宽高比
        double scaleX = (double) targetSize / originalWidth;
        double scaleY = (double) targetSize / originalHeight;
        double scale = Math.min(scaleX, scaleY);
        
        // 计算缩放后的尺寸
        int scaledWidth = (int) (originalWidth * scale);
        int scaledHeight = (int) (originalHeight * scale);
        
        // 计算居中位置
        int x = (targetSize - scaledWidth) / 2;
        int y = (targetSize - scaledHeight) / 2;
        
        // 绘制缩放后的图像
        g2d.drawImage(originalImage, x, y, scaledWidth, scaledHeight, null);
        
        System.out.println("🔧 Android缩放: " + originalWidth + "x" + originalHeight + 
                         " → " + scaledWidth + "x" + scaledHeight + 
                         " (scale=" + String.format("%.2f", scale) + ")");
    }
    
    /**
     * 判断图标是否可能是方形
     */
    private boolean isIconLikelySquare(BufferedImage image) {
        int width = image.getWidth();
        int height = image.getHeight();
        
        // 如果宽高比接近1:1，认为是方形图标
        double ratio = (double) Math.max(width, height) / Math.min(width, height);
        return ratio <= 1.2; // 允许20%的差异
    }
    
    /**
     * 绘制方形图标 - 使用智能填充
     */
    private void drawSquareIcon(Graphics2D g2d, BufferedImage originalImage, int targetSize) {
        int originalWidth = originalImage.getWidth();
        int originalHeight = originalImage.getHeight();
        
        // 计算缩放比例
        double scaleX = (double) targetSize / originalWidth;
        double scaleY = (double) targetSize / originalHeight;
        double scale = Math.min(scaleX, scaleY);
        
        // 计算缩放后的尺寸
        int scaledWidth = (int) (originalWidth * scale);
        int scaledHeight = (int) (originalHeight * scale);
        
        // 计算居中位置
        int x = (targetSize - scaledWidth) / 2;
        int y = (targetSize - scaledHeight) / 2;
        
        // 绘制图像
        g2d.drawImage(originalImage, x, y, scaledWidth, scaledHeight, null);
        
        // 如果缩放后还有空白区域，使用边缘像素填充
        if (scaledWidth < targetSize || scaledHeight < targetSize) {
            fillEmptyAreas(g2d, originalImage, x, y, scaledWidth, scaledHeight, targetSize);
        }
    }
    
    /**
     * 绘制矩形图标 - 保持宽高比
     */
    private void drawRectangularIcon(Graphics2D g2d, BufferedImage originalImage, int targetSize) {
        int originalWidth = originalImage.getWidth();
        int originalHeight = originalImage.getHeight();
        
        // 计算缩放比例，保持宽高比
        double scaleX = (double) targetSize / originalWidth;
        double scaleY = (double) targetSize / originalHeight;
        double scale = Math.min(scaleX, scaleY);
        
        // 计算缩放后的尺寸
        int scaledWidth = (int) (originalWidth * scale);
        int scaledHeight = (int) (originalHeight * scale);
        
        // 计算居中位置
        int x = (targetSize - scaledWidth) / 2;
        int y = (targetSize - scaledHeight) / 2;
        
        // 绘制图像
        g2d.drawImage(originalImage, x, y, scaledWidth, scaledHeight, null);
    }
    
    /**
     * 填充空白区域 - 使用边缘像素智能填充
     */
    private void fillEmptyAreas(Graphics2D g2d, BufferedImage originalImage, 
                               int x, int y, int scaledWidth, int scaledHeight, int targetSize) {
        // 获取边缘像素颜色
        Color edgeColor = getEdgeColor(originalImage);
        
        // 填充左右空白
        if (x > 0) {
            g2d.setColor(edgeColor);
            g2d.fillRect(0, 0, x, targetSize);
            g2d.fillRect(x + scaledWidth, 0, targetSize - x - scaledWidth, targetSize);
        }
        
        // 填充上下空白
        if (y > 0) {
            g2d.setColor(edgeColor);
            g2d.fillRect(0, 0, targetSize, y);
            g2d.fillRect(0, y + scaledHeight, targetSize, targetSize - y - scaledHeight);
        }
    }
    
    /**
     * 获取图像边缘的主要颜色
     */
    private Color getEdgeColor(BufferedImage image) {
        int width = image.getWidth();
        int height = image.getHeight();
        
        // 采样边缘像素
        int[] samples = new int[8];
        samples[0] = image.getRGB(0, 0); // 左上
        samples[1] = image.getRGB(width - 1, 0); // 右上
        samples[2] = image.getRGB(0, height - 1); // 左下
        samples[3] = image.getRGB(width - 1, height - 1); // 右下
        samples[4] = image.getRGB(width / 2, 0); // 上中
        samples[5] = image.getRGB(width / 2, height - 1); // 下中
        samples[6] = image.getRGB(0, height / 2); // 左中
        samples[7] = image.getRGB(width - 1, height / 2); // 右中
        
        // 计算平均颜色
        long r = 0, g = 0, b = 0, a = 0;
        for (int sample : samples) {
            Color color = new Color(sample, true);
            r += color.getRed();
            g += color.getGreen();
            b += color.getBlue();
            a += color.getAlpha();
        }
        
        return new Color(
            (int) (r / samples.length),
            (int) (g / samples.length),
            (int) (b / samples.length),
            (int) (a / samples.length)
        );
    }
}
